﻿using CoreEx.Common.Logging;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;

namespace CoreEx.Common.Implementation.Logging
{
    /// <summary>
    /// Installs a <see cref="TraceDebugLoggerFactory"/> if no other 
    /// logger factory exists in the <see cref="IServiceContainer"/>.   
    /// </summary>
    [PostProcessor]
    public class LoggerFactoryPostProcessor : IPostProcessor
    {
        private ILoggerFactory _defaultLoggerFactory;
        private readonly object _syncObject = new object();


        /// <summary>
        /// Allows a <see cref="T:LinFu.IoC.Interfaces.IPostProcessor"/> instance
        /// to inspect or modify the result of a service request.
        /// </summary>
        /// <param name="result">The <see cref="T:LinFu.IoC.Interfaces.IServiceRequestResult"/> created as a result of the container operation.</param>
        /// <seealso cref="T:LinFu.IoC.Interfaces.IServiceRequestResult"/>
        public void PostProcess(IServiceRequestResult result)
        {
            if (result.ServiceType == typeof(ILoggerFactory))
            {
                lock(_syncObject)
                {
                    if (result.ActualResult == null)
                        result.ActualResult = CreateDefaultLoggerFactory();
                }
            }
        }

        private ILoggerFactory CreateDefaultLoggerFactory()
        {
            if (_defaultLoggerFactory == null)
                _defaultLoggerFactory = new TraceDebugLoggerFactory();
            return _defaultLoggerFactory;
        }
    }
}
